(function($) {
    window.Nutzp = {
        verion : '1.0',
        transits:{}
    };
    window.Nutzp.Workspace = {
        open : function($wse,force) {
        },
        openTab : function(url, appId) {
        },
        closeTab : function(url, appId) {
        },
        activeTab : function(url, appId) {
        }
    };
    window.Nutzp.Workbench = {
        inited : false,
        workspaces : {},
        tpl : '',
        tpl2 : '',
        addWorkspace : function(workspaceId, workspace) {
            this.workspaces[workspaceId] = workspace;
        },
        addTab : function(workspaceId, tabId, text, icon, appId) {
            var wtid = '#' + workspaceId + '/' + tabId, atap = $("#ptab-" + appId);
            if (atap.length > 0) {
                $('#apptabs').find('.aptab').removeClass('active');
                atap.parents('.aptab').addClass('active');
                if (this.workspaces[workspaceId]) {
                    this.workspaces[workspaceId].activeTab(tabId, appId);
                }
            } else {
                var tab = $(this.tpl), tab2 = $(this.tpl2);
                tab.find('a.tabUrl').attr('href', wtid).attr('id', 'ptab-' + appId).text(text);
                tab.attr('data-content',workspaceId);
                tab2.find('a').attr('href', wtid).attr('id', 'drop-item-' + appId).text(text);
                if (icon) {
                    tab.find('span').addClass(icon);
                    tab2.find('a').addClass(icon).addClass('icon');
                }
                tab.hide();
                $('#apptabs').find('.aptab').removeClass('active');
                $('#pagetabs').append(tab);
                tab2.insertBefore($('#nzDivider'));
                this.doLayoutTabs();
                if (this.workspaces[workspaceId]) {
                    this.workspaces[workspaceId].openTab(tabId, appId);
                }
            }
        },
        init : function(workspaceId) {
            if (this.inited) {
                return;
            }
            var me = this;
            me.showMask();
            this.tpl = '<div class="aptab active"><div class="l"></div><div class="m"><span class="icn">&nbsp;</span><a class="tabUrl"></a></div><div class="r"><a href="#" class="close">&nbsp;</a></div></div>';
            this.tpl2 = '<li class="tab"><a href="#"></a></li>';

            $('#apptabs').delegate('.aptab', 'click', function() {//top tab clicked
                var overview = $(this).hasClass('overview');
                if (overview) {// workspace
                    var workspaceId = $(this).find('.tabUrl').attr('href').replace('#', '');
                    me.openWorkspace(workspaceId,true);
                    $('.aptab').not($(this)).removeClass('highlight');
                    $(this).addClass('highlight');
                } else {// page tabs
                    var tab = $(this).find('.tabUrl'), workId = tab.attr('href').replace('#', '').split('/'), appID = tab.attr('id');
                    appID = appID.replace('ptab-', '');
                    var ids = workId.slice(1);
                    me.activeTab(workId[0], ids.join('/'), appID);
                }
                $('#apptabs').find('.aptab').not($(this)).removeClass('active');
                $(this).addClass('active');
                return false;
            });

            $('#pagetabs').delegate('.close', 'click mouseover mouseout', function(event) {
                if (event.type == 'mouseover') {
                    $(this).addClass('ovr');
                } else if (event.type == 'mouseout') {
                    $(this).removeClass('ovr');
                } else {
                    me.closeTab($(this).parents('.aptab'));
                }
                return false;
            });

            $('#moretabs').hover(function() {
                $(this).data('hide', false);
            }, function(e) {
                var oft = $(this).offset(), sW = $(this).outerWidth() - 1, sH = $(this).outerHeight() - 1;
                var cX = e.clientX, cY = e.clientY;
                if (cX < oft.left || cX > oft.left + sW || cY < oft.top || cY > oft.top + sH) {
                    $(this).hide();
                }
                return false;
            });

            $('#tabOverView').click(function() {
                var tabs = $('#moretabs').find('a');
                if (tabs.length < 3) {
                    return false;
                }
                var oft = $(this).offset();
                var menu = $($(this).attr('href'));
                menu.css({
                    top : 65,
                    right : 1,
                    left : 'auto'
                }).show();
                menu.data('hide', true);
                setTimeout(function() {
                    if (menu.data('hide')) {
                        menu.data('hide', false);
                        menu.hide();
                    }
                }, 5000);
                return false;
            });

            $(window).resize(function() {
                me.doLayoutTabs();
                me.doLayoutIFrames();
                me.doLayoutIcons();
                if ($('#overlay img:visible').length > 0) {
                    me.showMask(null, true);
                }
            });

            $('#moretabs').delegate('a', 'click', function() {
                $('#moretabs').hide();
                var m = $(this);
                if (this.id == 'nzCloseAll') {
                    me.closeAllTabs();
                } else if (this.id == 'nzCloseOthers') {
                    me.closeOthersTabs();
                } else {
                    var atr = m.attr('href'), workId = atr.replace('#', '').split('/');
                    var ids = workId.slice(1), appID = m.attr('id').replace('drop-item-', '');
                    me.activeTab(workId[0], ids.join('/'),appID);
                    $('#apptabs').find('.aptab').removeClass('active');
                    try {
                        $('#ptab-'+appID).parents('.aptab').addClass('active');
                    } catch (e) {
                    }
                }
                return false;
            });

            $('#icons').delegate('a', 'click', function() {
                var app = $(this), aspan = app.find('span').text(), id = app.attr('href'), cls = app.attr('cls'), appId = app.attr('id');
                Nutzp.Workbench.addTab('desktop', id, aspan, cls, appId);
                return false;
            });
            $('body').bind('doTabsLayout', me.doLayoutTabs);

            var workspace = me.getWorkspace(workspaceId);
            workspace.click();
            me.doLayoutTabs();
            me.doLayoutIFrames();
            me.doLayoutIcons();
            me.hideMask();
            this.inited = true;
        },
        doLayoutTabs : function() {
            var ptw = $('#pagetabs').width();
            var ptbs = $('#pagetabs .aptab'), ptc = ptbs.length;
            if (ptc > 0) {
                var tw = (ptw - 15) / ptc;
                tw = tw > 150 ? 150 : tw;
                ptbs.width(tw).show();
            }
        },
        doLayoutIFrames : function() {
            var ws = $("#workspace"), wh = ws.height();
            ws.find('iframe').css({
                height : wh
            });
        },
        doLayoutIcons : function() {
            var ws = $("#workspace"), ww = ws.width(), wh = ws.height();
            var shortcuts = $('#icons').find('.shortcut');
            var w = 64, h, x = 15, y = 15, cx = 0, sh = 0, en;
            $.each(shortcuts, function(i, n) {
                en = $(n);
                sh = en.data('height');
                if (!sh) {
                    sh = en.height();
                    en.data('height', sh);
                }
                if (sh + y > wh) {
                    y = 15;
                    cx++;
                    x += w * cx + 15;
                }
                en.css({
                    left : x,
                    top : y
                });
                y += sh + 15;
            });
        },
        showMask : function(text, keep) {
            text = text ? text : '处理中,请稍候...';
            var ov = $('#overlay'), msg = ov.find('div.msg');
            ov.show();
            if (!keep) {
                msg.html(text);
            }
        },
        setMask : function(text) {
            $('#overlay').find('div.msg').html(text);
        },
        hideMask : function() {
            var ov = $('#overlay').fadeOut(350);
        },
        openWorkspace : function(workspaceId,force) {
            $('#workspace').find('.workspace').not('#' + workspaceId).hide();
            $('#maintabs').find('.aptab').not('.' + workspaceId).removeClass('highlight');
            this.getWorkspace(workspaceId).addClass('highlight');
            var wse = $('#' + workspaceId);
            var ws = this.workspaces[workspaceId];            
            if (ws) {
                ws.open(wse,force);
            }
            return ws;
        },
        closeTab : function(tab, appID) {
            if (!tab) {
                tab = $('#ptab-' + appID).parents('.aptab');
            }
            var nt = tab.next('.aptab'), pt = tab.prev('.aptab'), ated = tab.hasClass('active'), tabA = false;
            var ctab = tab.find('.tabUrl'), wtid = ctab.attr('href'), workId = wtid.replace('#', '').split('/');
            var ws = this.openWorkspace(workId[0]), appID = ctab.attr('id').replace('ptab-', '');
            if (ws) {
                var ids = workId.slice(1);
                ws.closeTab(ids.join('/'), appID);
            }
            tab.hide().remove();
            $("#drop-item-" + appID).parents('li').remove();
            if (ated) {
                if (nt.length > 0) {
                    nt.click();
                    tabA = true;
                } else if (pt.length > 0) {
                    pt.click();
                    tabA = true;
                }
            }
            if (!tabA) {
                if (nt.length == 0 && pt.length == 0) {
                    $('#maintabs').find('.highlight').click();
                }
            }
            $('body').trigger('doTabsLayout');
        },
        activeTab : function(workspaceId, tabId, appID) {
            var ws = this.openWorkspace(workspaceId);
            if (ws) {
                ws.activeTab(tabId, appID);
            }
        },
        openTab : function(workspaceId, tabId, appID) {
            var atap = $("#ptab-"+appID);
            if (atap.length > 0) {
                $('#apptabs').find('.aptab').removeClass('active');
                atap.parents('.aptab').addClass('active');
            }
            var ws = this.openWorkspace(workspaceId);
            if (ws) {
                ws.openTab(tabId,appID);
            }
            $('body').trigger('doTabsLayout');
        },
        getWorkspace : function(workspaceId) {
            return $('#maintabs').find('.aptab a[href=#' + workspaceId + ']').parents('.aptab');
        },
        closeAllTabs : function() {
            var htab = $('#maintabs').find('.active');
            if (htab.length == 0) {
                htab = $('#maintabs').find('.highlight');
                if (htab.length == 0) {
                    htab = $('#maintabs').find('.aptab:first');
                }
            }
            $('#pagetabs').empty();
            $('#moretabs').find('.tab').remove();
            $('#desktop').find('.app').remove();
            if (htab.length > 0) {
                htab.click();
            }
        },
        closeOthersTabs : function() {
            var tab, wid, wids, wb, mtabs = $('#moretabs'), me = Nutzp.Workbench,taba;
            $('#pagetabs').find('.aptab').each(function(i, n) {
                tab = $(n);
                if (!tab.hasClass('active')) {
                    taba = tab.find('a.tabUrl');
                    wid = taba.attr('href');
                    appID = taba.attr('id').replace('ptab-','');
                    wids = wid.replace('#', '').split('/');
                    tab.remove();
                    $('#drop-item-'+appID).parents('li').remove();
                    wsid = wids[0];
                    wb = me.getWorkspace(wsid);
                    if (wb.length > 0 && !wb.hasClass('active') && !wb.hasClass('highlight')) {
                        $('#' + wsid).remove();
                    } else if (wb.hasClass('highlight') && me.workspaces[wsid]) {
                        var tabId = wids.slice(1);
                        tabId = tabId.join('/');
                        me.workspaces[wsid].closeTab(tabId,appID);
                    }
                }
            });
            if ($('#pagetabs').find('.aptab').length == 0) {
                var htab = $('#maintabs').find('.highlight');
                if (htab.length == 0) {
                    htab = $('#maintabs').find('.aptab:first');
                }
                htab.click();
            }
        }
    };
})(window.jQuery);

var Desktop = $.extend({}, Nutzp.Workspace, {
    appTpl : '<div class="app"><iframe frameborder="0" onload="Desktop.onload()"></iframe></div>',
    attachCallback : null,
    iframeCallback : null,
    iframeModal : null,
    open : function(desk,force) {        
        var desk = $('#desktop'),tabs = $('#pagetabs').find(".active[data-content='desktop']");
        if(force === true || tabs.length == 0){
            desk.find('.app').hide();
            $('#icons').show();
            $("#widgets").show();
        }
        desk.show();
    },
    openTab : function(tabId,appID) {
        var desk = $('#desktop'), app = desk.find('#iframe-'+appID);
        $('#icons').hide();
        $("#widgets").hide();
        desk.find('.app').hide();
        if (app.length > 0) {
            app.parents('.app').show();
        } else {           
            Nutzp.Workbench.showMask('正在加载页面...');            
            app = $(this.appTpl);
            var iframe = app.find('iframe');
            iframe.attr('src', tabId);
            iframe.attr('id','iframe-'+appID);
            desk.append(app);
            Nutzp.Workbench.doLayoutIFrames();
        }
    },
    activeTab : function(tabId,appID) {
        //Nutzp.Workbench.showMask();
        var desk = $('#desktop'), app = desk.find('#iframe-'+appID);
        $('#icons').hide();
        $("#widgets").hide();
        desk.find('.app').hide();
        app.parents('.app').show();
        //app.attr('src',tabId);
    },
    closeTab : function(tabId,appID) {
        var desk = $('#desktop'), app = desk.find('#iframe-'+appID);
        app.parents('.app').remove();
    },
    onload : function() {
        Nutzp.Workbench.hideMask();
    },
    iframeOnload : function() {
        Nutzp.Workbench.hideMask();
        if (Desktop.iframeModal) {
            Desktop.iframeModal.modal({
                backdrop: true,
                'static': true,
                show: true
            });
        }
    },
    iframeMask : function(modal) {
        this.iframeModal = modal;
        Nutzp.Workbench.showMask('正在加载...', true);
    },
    openAttachDialog : function(callback) {
        this.attachCallback = callback;
        this.iframeMask($('#pic-modal'));
        $('#picframe').attr('src', './share/?_t=d');
    },
    openIframeDialog : function(title, src, callback,width,height) {
        Nutzp.Workbench.showMask('正在加载...', true);
        var modal = $('#iframe-modal'),w,h;
        if(width && height){
            w = width;
            h = height;            
        }else{
            w = 800;
            h = 500;            
        }
        modal.css({
                width:w,
                height:h,
                'margin-left': -w/2,
                'margin-top': -h/2
        });
        modal.find('.modal-body').css({
            height:h-100,
            'max-height':h-100
        });
        
        this.iframeCallback = callback;
        this.iframeMask($('#iframe-modal'));
        $('#iframe-title').text(title);
        $('#modal-inner-frame').attr('src', src);
    },
    hideWaitMask : function() {
        Nutzp.Workbench.hideMask();
    },
    showWaitMask : function(msg) {
        Nutzp.Workbench.showMask(msg, false);
    },
    notify : function(notfiy, timeout) {

    }
});
Nutzp.Workbench.addWorkspace('desktop', Desktop);

function showTransitDialog(transit,url,callback){
    var tf = Nutzp.transits[transit];
    if($.isFunction(tf)){
        tf(transit,url,callback);
    }
}
function openDesktopPanel(url,title,icon,appID){
    Nutzp.Workbench.addTab('desktop', url, title, icon, appID);
    return false;
}
$(function() {
    Nutzp.Workbench.init('desktop');
    $('.btn-close-form').click(function() {
        $('.modal').modal('hide');
    });
    $('#clear_cache').click(function(){
        Desktop.showWaitMask('正在清空缓存,请稍后...');
        $.ajax({
            url:'../ajax.php?ajaxCmd=clear_cache',
            success:function(data){
                if(data.msg){
                    alert(data.msg);
                }
                Desktop.hideWaitMask();
            }
        });
        return false;
    });
    $('#modal-inner-frame,#picframe').load(Desktop.iframeOnload);
    $('#btn-attac-done').click(function() {
        $('#pic-modal').modal('hide');
        if ($.isFunction(Desktop.attachCallback)) {
            var frame = document.getElementById("picframe").contentWindow;
            var attach = frame.getSelectedAttachment();
            frame.clearSelected();
            Desktop.attachCallback(attach);
        }
    });
    $('#btn-iframe-done').click(function() {
        $('#iframe-modal').modal('hide');
        if ($.isFunction(Desktop.iframeCallback)) {
            var frame = document.getElementById("modal-inner-frame").contentWindow;
            Desktop.iframeCallback(frame);
        }
    });
    $('.stuffbox').delegate('.handlediv','click',function(){
        var me = $(this),sutffbox= me.parents('.stuffbox');
        if(sutffbox.hasClass('closed')){
            sutffbox.removeClass('closed');
        }else{
            sutffbox.addClass('closed');            
        }
    });
    $('#widgets-sp').click(function(){
        var me = $(this), widget = $('#widgets');
        if(widget.hasClass('folded')){
            widget.removeClass('folded');
            me.attr('title','收起桌面小工具');
        }else{
            widget.addClass('folded'); 
            me.attr('title','隐藏桌面小工具');
        }
    });
}); 